package com.xinqi.util.pipeline;

import com.xinqi.config.JedisConfig;
import com.xinqi.util.GCUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;

import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author xin麒
 * @date 2023/8/25 17:27
 * GC操作参考：
 * https://blog.csdn.net/zhibo_lv/article/details/107934980
 * https://blog.csdn.net/m0_46330462/article/details/116560911
 * 测试过程test包的com.xinqi.august25.TestField
 */
public class SinglePipeline {
    private Logger logger = LoggerFactory.getLogger(SinglePipeline.class);
    private volatile Pipeline pipeline;
    private AtomicBoolean lock = new AtomicBoolean(true);

    private Jedis jedis;
    private JedisConfig jedisConfig;
    public SinglePipeline(@Autowired JedisConfig jedisConfig) {
        this.jedisConfig = jedisConfig;
    }
    public Pipeline getPipeline() {
        if (pipeline == null){
            synchronized (this){
                if (pipeline == null){
//                    this.pipeline =  jedisPool.getResource().pipelined();
//                    JedisConfig jedisConfig = new JedisConfig();
                    JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
                    jedisPoolConfig.setMaxIdle(1);
                    jedisPoolConfig.setMinIdle(1);
                    jedisPoolConfig.setMaxTotal(jedisConfig.getMaxActive());
                    jedis = new JedisPool(jedisPoolConfig,
                            jedisConfig.getHost(),
                            jedisConfig.getPort(),
                            jedisConfig.getTimeout(),
                            jedisConfig.getPassword()
                    ).getResource();
                    pipeline = jedis.pipelined();
                }
            }
        }
        return pipeline;
    }

    public void unlock() {
        lock.getAndSet(true);
    }

    public boolean lock() {
        return lock.compareAndSet(true, false);
    }

    public void get(String key) {
        getPipeline().get(key);
    }

    public List<Object> syncAndReturnAll() {
        return getPipeline().syncAndReturnAll();
    }

    public void clear() {
        getPipeline().clear();
    }

    public void zrangeWithScores(String key, int begin, int end) {
        getPipeline().zrangeWithScores(key,begin,end);
    }

    public void set(String key, String val) {
        getPipeline().set(key,val);
    }

    public void helpGC(){
        if (pipeline == null) return;
        pipeline.close();
        jedis.close();
        GCUtil.helpGC(this);
    }


}
